import router from './router'
import store from './store'

import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

import { asyncRouter } from './router/index'
// import { getUserInfo } from '@/utils/auth'
// import { rolePermission } from '@/api/login'

const whiteList = ['/login'] // no redirect whitelist

function flattenArr (tree, arr = []) {
  tree.forEach(item => {
    // 结构item
    const { menuList, ...props } = item
    // 添加除了menuList的属性
    arr.push(props)
    if (menuList) {
      // 存在menuList递归将所有节点加入到结果集中
      flattenArr(menuList, arr)
    }
  })
  return arr
}

router.beforeEach(async (to, from, next) => {
  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  const hasGetUserInfo = store.getters.role
  // console.log(hasGetUserInfo)
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      return
    } else {
      // console.log(store.getters.btnList);
      // console.log(hasGetUserInfo);
      if (!hasGetUserInfo) {
        const { data } = await store.dispatch('user/getUserInfo')

        const arr = []

        flattenArr(data, arr)
        // console.log(arr);
        // 按钮权限
        const arr2 = arr.filter(item => item.menuType == 'F')
        const btnList = arr2.map(item => item.path)

        store.commit('user/updateBtnList', btnList)
        // 获取页面权限
        const arrPage = arr.filter(
          item => item.menuType == 'M' || item.menuType == 'C'
        )
        // console.log(arrPage)

        const routeList = arrPage.map(item => item.path)
        // console.log(11, asyncRouter)
        // console.log(22, routeList)
        const actionRouter = asyncRouter.filter(item => {
          return routeList.includes(item.name)
        })
        // console.log(actionRouter)
        // 改二级路由
        actionRouter.forEach(obj => {
          // 遍历每个对象中的数组
          obj.children.forEach(item => {
            // 为每个对象添加键值对
            if (!routeList.includes(item.name)) {
              item.hidden = true
            } else {
              item.hidden = false
              
            }
          })
        })
        // console.log(actionRouter)
        store.commit('user/updateRoutes', actionRouter)

        router.addRoutes([
          ...actionRouter,
          { path: '*', redirect: '/404', hidden: true }
        ])
        next(actionRouter[0].path)
        // next({ ...to, replace: true })
      } else {
        next()
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login`)
      // next()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
})
